<html>
<script src="alice.core.js"></script>
<script src="alice.plugins.cheshire.js"></script>
<script type="text/javascript">

// this event is fired when the device detects any kind of motion.
window.addEventListener("devicemotion", function(event) {

		// event.accelerationIncludingGravity.x, .y, .z will give the respective co-ordinates of the device (> 8 decimal points in precision)
		// magnify the movement 100 fold by multiplying. + and - 4 will move the center position to center of the device rather than top left
		var ax = (fnRoundToZero(event.accelerationIncludingGravity.x)+4) * 100;
		var ay = (fnRoundToZero(event.accelerationIncludingGravity.y)-4) * -100;
		var az = (fnRoundToZero(event.accelerationIncludingGravity.z)) * 100;
		
		// change style - position property of the ball div so as to move it.
		document.getElementById("ball").style.position = "fixed";
		// restrict around the edges
		if (ax < 920 && ax > 0)
		{
			document.getElementById("ball").style.left = ax+"px";
		}
		if (ay < 450 && ay > 50)
		{
			document.getElementById("ball").style.top = ay+"px";
		}
		// note down the co-ordiates
		document.getElementById("positions").innerHTML = ax + "<br/>" + ay + "<br/>" + az;

}, true);

// Simple rounding function. Round the 8 decimal point numbers given by device motion event to 2 digit.
function fnRoundToZero(num)
{
	return Math.round(num*100)/100;
}


// when tapped on the ball, make the ball bounce using AliceJS
function bounce()
{
	var a = alice.init();
	// Call the pauseBounce funciton afte 2 seconds to stop the bouncing
	window.setTimeout("pauseBounce()",2000);
	var audio = new Audio('bounce.wav');
	audio.play();
	var elems = ["ball"];
	a.bounce(elems, 
			{
				 from: "100%", to: "150%"
			}, false, {
                "value": "250ms"
            });
	
}
 
 
// Stop the bouncing effect after 2 seconds
function pauseBounce()
{
	var a = alice.init();
	var elems = ["ball"];
	a.bounce(elems, "", "", "","","","","","paused");
}
</script>
<body>
	<p id ="positions" style="position:fixed; top:0; right: 500px">
	</p>
	<div id="x" height="100%" width="100%">
		<div id="ball">
			<img src='ball.jpg' alt='x' height='100px' onClick="bounce()"/>
		</div>
		
	</div>
	
</html>